package com.mp.approvalreq.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.*;
import com.mp.approvalreq.entity.common.Constants;
import com.mp.approvalreq.entity.dto.RedPointDTO;
import com.mp.user.entity.User;
import com.mp.user.entity.dto.UserStatusDTO;
import com.mp.user.entity.po.UserStatus;
import com.mp.user.service.UserServicePrx;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by liuqi on 2018/6/21.
 */
public class RocketUtils {

    private static final Logger logger = LoggerFactory.getLogger(RocketUtils.class);

    // 假期管理相关模版
    private static List<Integer> LEAVE_TEMPLATE_TYPES = Arrays.asList(Template.LEAVE, Template.COMPENSATORY_LEAVE, Template.DAYS_OFF);
    // 作废通知考勤相关模版
    private static List<Integer> CHECK_IN_DISABLE_TEMPLATE_TYPES = Arrays.asList(2, 3, 5, 7, 8, 9, 12);
    // 批准通知考勤相关模版
    private static List<Integer> CHECK_IN_CONFIRM_TEMPLATE_TYPES = Arrays.asList(2, 5, 8, 9, 12);
    // 用户状态相关模版
    private static List<Integer> USER_STATUS_TEMPLATE_TYPES = Arrays.asList(2, 3, 8);

    /**
     * 发送单条推送
     *
     * @param userId
     * @param requestId
     * @param pushTitle
     */
    private static void pushOneMsg(Integer userId, Integer requestId, String pushTitle, String objectJson) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", userId);
            jsonObject.put("objectClass", Constants.APPROVAL_MODULE_NAME);
            jsonObject.put("objectId", requestId);
            jsonObject.put("objectTitle", pushTitle);
            jsonObject.put("objectJson", objectJson);

            logger.info(jsonObject.toJSONString());

            MQUtils.sendMessage(Constants.MQ_PUSH_TOPIC, Constants.MQ_PUSH_TAG_ONE, jsonObject);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "消息推送报错", e.getMessage());
        }
    }

    /**
     * 发送多条一样的推送,给不同的人
     *
     * @param requestId
     * @param pushTitle
     */
    public static void pushManyToOneMsg(Collection<Integer> userIdList, Integer requestId, String pushTitle, String objectJson) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userIdList", userIdList);
            jsonObject.put("objectClass", Constants.APPROVAL_MODULE_NAME);
            jsonObject.put("objectId", requestId);
            jsonObject.put("objectTitle", pushTitle);
            jsonObject.put("objectJson", objectJson);

            logger.info(jsonObject.toJSONString());

            MQUtils.sendMessage(Constants.MQ_PUSH_TOPIC, Constants.MQ_PUSH_TAG_MANY_TO_ONE, jsonObject);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "消息推送报错", e.getMessage());
        }
    }

    public static void pushToRefresh(User user, Collection<Integer> contactIds) {
        try {
            JSONObject param = new JSONObject();
            param.put("companyId", user.getCompanyId());
            param.put("contactIds", Utils.collection2string(contactIds));
            param.put("moduleType", "Approval");
            MQUtils.sendMessage(Constants.MQ_BASE_TOPIC, Constants.MQ_BASE_TAG_CONTACT_STATUS, param);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            EmailUtils.sendMail("发消息出错", e);
        }
    }

    public static void pushToRefresh(Integer companyId, Collection<Integer> contactIds) {
        try {
            JSONObject param = new JSONObject();
            param.put("companyId", companyId);
            param.put("contactIds", Utils.collection2string(contactIds));
            param.put("moduleType", "Approval");
            MQUtils.sendMessage(Constants.MQ_BASE_TOPIC, Constants.MQ_BASE_TAG_CONTACT_STATUS, param);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            EmailUtils.sendMail("发消息出错", e);
        }
    }

    public static void pushToRefresh(User user) {
        try {
            JSONObject param = new JSONObject();
            param.put("companyId", user.getCompanyId());
            param.put("contactIds", user.getContactId());
            param.put("moduleType", "Approval");
            MQUtils.sendMessage(Constants.MQ_BASE_TOPIC, Constants.MQ_BASE_TAG_CONTACT_STATUS, param);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            EmailUtils.sendMail("发消息出错", e);
        }

    }

    public static void pushToCompanyRefresh(Integer companyId) {
        JSONObject param = new JSONObject();
        param.put("companyId", companyId);
        param.put("moduleType", "Approval");
        MQUtils.sendMessage(Constants.MQ_BASE_TOPIC, Constants.MQ_BASE_TAG_COMPANY_STATUS, param);
    }


    /**
     * 发送权限消息（后续作废）
     *
     * @param allJudger
     * @param companyId
     */
    @Deprecated
    public static void sendAddAuthMsg(String allJudger, Integer companyId) {
        JSONObject jo = new JSONObject();
        jo.put("companyId", companyId);
        jo.put("authType", 21);
        jo.put("addContactIds", allJudger);

        logger.info("权限消息: " + jo.toJSONString());

        MQUtils.sendMessage(Constants.MQ_TOPIC_AUTH, Constants.MQ_TAG_AUTH_ADD, jo);
    }


    /**
     * 通知人事重结算调休时长
     *
     * @param companyId
     * @param companyInfoId
     */
    public static void sendHrCalculateDaysOff(Integer companyId, Integer companyInfoId) {
        JSONObject jo = new JSONObject();
        jo.put("companyId", companyId);
        jo.put("companyInfoId", companyInfoId);

        MQUtils.sendMessage(Constants.MQ_HR_TOPIC, Constants.MQ_TAGS_RECALCULATE_DAYS_OFF_TIME, jo);
    }

    public static void clearRequestRedPoint(Integer requestId, Integer companyId) {
        try {
            RedPointDTO param = new RedPointDTO();
            param.setRequestId(requestId);
            param.setCompanyId(companyId);
            logger.info("消红点:{}", param);
            MQUtils.sendMessage(Constants.MQ_APPROVAL_TOPIC, Constants.MQ_TAG_CLEAR_RED_POINT, param);
            pushToCompanyRefresh(companyId);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            EmailUtils.sendMail("消红点失败", e);
        }
    }

    public static void clearUserRedPoint(Integer requestId, User user) {
        try {
            RedPointDTO dto = new RedPointDTO();
            dto.setRequestId(requestId);
            dto.setCompanyInfoId(user.getCompanyInfoId());
            dto.setCompanyId(user.getCompanyId());

            logger.info("消红点:{}", dto);
            MQUtils.sendMessage(Constants.MQ_APPROVAL_TOPIC, Constants.MQ_TAG_CLEAR_RED_POINT, dto);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            EmailUtils.sendMail("消红点失败", e);
        }
    }

    /**
     * 作废审批的相关推送
     *
     * @param request
     * @throws Throwable
     */
    private static void pushCancelApprovalMsg(Request request) {
        try {
            UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);

            // 推送申请人
            User user = userService.getUserByContactId(request.getApplicant());
            String objectJson = request.getRequestDkey() + "," + request.getTemplateId() + "," + request.getVersion();

            if (Utils.isNotNull(user.getUserId())) {
                pushOneMsg(user.getUserId(), request.getRequestDkey(), "您有一条相关审批已被作废", objectJson);
            }
            pushToRefresh(user);

            if (Utils.isNotNull(request.getProxyContactId()) && request.getProxyContactId() > 0) {
                // 推送申请人
                User proxyUser = userService.getUserByContactId(request.getProxyContactId());

                if (Utils.isNotNull(proxyUser.getUserId())) {
                    pushOneMsg(proxyUser.getUserId(), request.getRequestDkey(), "您有一条相关审批已被作废", objectJson);
                }
                pushToRefresh(proxyUser);
            }
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "作废审批的相关推送", e.getMessage());
        }
    }

    private static void pushFinishRequestMsg(Request request) {
        try {
            UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);

            User user = userService.getUserByContactId(request.getApplicant());
            String pushApprovalId = request.getRequestDkey() + "," + request.getTemplateId() + "," + request.getVersion();
            String pushTitle = "您的" + request.getRequestName() + "申请已被批准";

            if (Utils.isNotNull(user.getUserId())) {
                pushOneMsg(user.getUserId(), request.getRequestDkey(), pushTitle, pushApprovalId);
            }

            // 代申请人
            if (Utils.isNotNull(request.getProxyContactId()) && request.getProxyContactId() > 0) {
                String title = "您的" + request.getRequestName() + "代申请已被批准";
                User proxyUser = userService.getUserByContactId(request.getProxyContactId());
                pushOneMsg(proxyUser.getUserId(), request.getRequestDkey(), title, pushApprovalId);
            }

            if (StringUtils.isNotEmpty(request.getCc())) {
                List<User> ccs = userService.getUserListByContactIds(request.getCc());
                List<Integer> userIdList = ccs.stream().map(User::getUserId).collect(Collectors.toList());
                if (ListHelper.isNotNullEmpty(userIdList)) {
                    String pushCcTitle = "您有一条新的审批抄送";
                    pushManyToOneMsg(userIdList, request.getRequestDkey(), pushCcTitle, pushApprovalId);
                }
            }
            Set<Integer> contactIds = new HashSet<>();
            if (StringUtils.isNotEmpty(request.getCc())) {
                contactIds.addAll(Utils.string2list(request.getCc()));
            }
            contactIds.add(user.getContactId());
            pushToRefresh(user, contactIds);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "推送已批准的信息", e.getMessage());
        }
    }

    /**
     * 给下一个审批人的推送
     *
     * @param request
     * @param pushUserIds
     */
    public static void pushApproveRequestMsg(Request request, Collection<Integer> pushUserIds) {
        try {
            String pushApprovalId = request.getRequestDkey() + "," + request.getTemplateId() + "," + request.getVersion();
            String pushTitle = "您有一条新审批待处理";

            if (Utils.isNotEmpty(pushUserIds)) {
                pushManyToOneMsg(pushUserIds, request.getRequestDkey(), pushTitle, pushApprovalId);
            }
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "给下一个审批人的推送", e.getMessage());
        }
    }


    /**
     * 推送驳回的消息给申请人
     *
     * @param request
     */
    public static void pushRefuseRequestMsg(Request request) {
        try {
            UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);

            User user = userService.getUserByContactId(request.getApplicant());
            String pushApprovalId = request.getRequestDkey() + "," + request.getTemplateId() + "," + request.getVersion();

            if (Utils.isNotNull(user.getUserId())) {
                pushOneMsg(user.getUserId(), request.getRequestDkey(), "您有一条审批申请未通过,点击查看详情", pushApprovalId);
            }
            pushToRefresh(user);

            if (Utils.isNotNull(request.getProxyContactId()) && request.getProxyContactId() > 0) {
                User proxyUser = userService.getUserByContactId(request.getProxyContactId());

                pushOneMsg(proxyUser.getUserId(), request.getRequestDkey(), "您有一条代申请审批未通过,点击查看详情", pushApprovalId);

                pushToRefresh(proxyUser);
            }


        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "推送驳回的消息给申请人", e.getMessage());
        }
    }

    public static void sendLeaveTypeMessage(Request request) {
        try {
            MQUtils.sendMessage(Constants.MQ_HR_TOPIC, Constants.MQ_TAGS_STAFF_APPLY_LEAVE, request.getLeave());
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "请假类型消息出错", e.getMessage());
        }
    }

    // =========================统一处理审批评论的消息=========================

    public static void pushToOthers(List<Integer> userIds, Request request, String pushMsg) {
        if (!Utils.isEmpty(userIds)) {
            String objJson = request.getRequestDkey() + "," + request.getTemplateId() + "," + request.getVersion();
            String objTitle = "您有一条新的审批评论:" + pushMsg;

            pushManyToOneMsg(userIds, request.getRequestDkey(), objTitle, objJson);
        }
    }


    public static void pushToAtUsers(List<Integer> atUserIds, Request request, String pushMsg, String commentUser) {
        if (Utils.isEmpty(atUserIds)) {
            return;
        }
        String objJson = request.getRequestDkey() + "," + request.getTemplateId() + "," + request.getVersion();
        String objTitle = commentUser + "@您:" + pushMsg;
        pushManyToOneMsg(atUserIds, request.getRequestDkey(), objTitle, objJson);
    }

    // =========================统一处理操作审批的消息=========================

    /**
     * 批准审批
     *
     * @param user
     * @param request
     * @param nextFlows
     */
    public static void sendConfirmMsg(User user, Request request, List<Flow> nextFlows) throws Throwable {
        logger.info("===============批准审批发消息===============");
        if (request.getFinished() == Finished.AGREED) {
            pushFinishRequestMsg(request);

            sendConfirmMsgToCheckIn(user, request);

            sendStatusMsgToUser(request, Constants.ACTIVE_STATUS);

            //工作动态消息
            if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
                UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
                User applicant = userServicePrx.getUserByContactId(request.getApplicant());
                RocketUtils.sendApprovalWorkTrendsMsg(request, user, "批准" + applicant.getContactName() + "的申请", request.getRequestName());
            }
        } else {
            pushToNextFlows(user, request, nextFlows);
        }
        pushToRefresh(user);
    }

    /**
     * 驳回审批
     *
     * @param user
     * @param request
     */
    public static void sendRefuseMsg(User user, Request request) throws Throwable {
        if (request.getFinished() == Finished.REFUSED) {
            logger.info("===============驳回审批发消息===============");

            pushRefuseRequestMsg(request);

            sendDisableMsgToCheckIn(user, request);

            sendDisableMsgToHr(user, request);

            sendHrCalculateDaysOff(user, request);

            //工作动态消息
            if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
                UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
                User applicant = userServicePrx.getUserByContactId(request.getApplicant());
                sendApprovalWorkTrendsMsg(request, user, "驳回" + applicant.getContactName() + "的申请", request.getRequestName());
            }
        }
        pushToRefresh(user);
    }

    /**
     * 归档审批
     *
     * @param user
     * @param request
     */
    public static void sendFileMsg(User user, Request request) throws Throwable {
        logger.info("===============归档审批发消息===============");
        pushToRefresh(user);

        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
            User applicant = userServicePrx.getUserByContactId(request.getApplicant());
            sendApprovalWorkTrendsMsg(request, user, "归档" + applicant.getContactName() + "的申请", request.getRequestName());
        }
    }


    /**
     * 作废审批
     *
     * @param user
     * @param request
     */
    public static void sendCancelMsg(User user, Request request) throws Throwable {
        logger.info("===============作废审批发消息===============");
        clearRequestRedPoint(request.getRequestDkey(), user.getCompanyId());

        pushCancelApprovalMsg(request);

        sendDisableMsgToCheckIn(user, request);

        sendStatusMsgToUser(request, Constants.DISABLE_STATUS);

        sendDisableMsgToHr(user, request);

        sendHrCalculateDaysOff(user, request);

        //工作动态消息
        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
            User applicant = userServicePrx.getUserByContactId(request.getApplicant());
            sendApprovalWorkTrendsMsg(request, user, "作废" + applicant.getContactName() + "的申请", request.getRequestName());
        }
    }

    /**
     * 撤销归档审批
     *
     * @param user
     * @param request
     */
    public static void sendWithdrawFiledMsg(User user, Request request) throws Throwable {
        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
            User applicant = userServicePrx.getUserByContactId(request.getApplicant());
            sendApprovalWorkTrendsMsg(request, user, "撤销归档" + applicant.getContactName() + "的申请", request.getRequestName());
        }
    }

    /**
     * 撤销提前结束审批
     *
     * @param user
     * @param request
     */
    public static void sendCancelPauseRequestMsg(User user, Request request) throws Throwable {
        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            if (Objects.equals(user.getCompanyInfoId(), request.getApplicantCiid())) {
                // 作废自己的
                sendApprovalWorkTrendsMsg(request, user, "撤销提前结束", request.getRequestName());
            } else {
                // 作废他人的
                UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
                User applicant = userServicePrx.getUserByContactId(request.getApplicant());
                sendApprovalWorkTrendsMsg(request, user, "撤销提前结束" + applicant.getContactName() + "的申请", request.getRequestName());
            }
        }
    }

    /**
     * 撤销批准
     *
     * @param user
     * @param request
     */
    public static void sendWithdrawApproveMsg(User user, Request request) throws Throwable {
        // 重算调休时长
        if (Objects.equals(request.getDefaultType(), Template.DAYS_OFF)) {
            sendHrCalculateDaysOff(user.getCompanyId(), request.getApplicantCiid());
        }
        //工作动态消息
        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
            User applicant = userServicePrx.getUserByContactId(request.getApplicant());
            RocketUtils.sendApprovalWorkTrendsMsg(request, user, "撤销批准" + applicant.getContactName() + "的申请", request.getRequestName());
        }
    }

    /**
     * 撤销申请
     *
     * @param user
     * @param request
     */
    public static void sendWithdrawApplyMsg(User user, Request request) {
        logger.info("===============撤销申请发消息===============");
        clearRequestRedPoint(request.getRequestDkey(), user.getCompanyId());

        sendDisableMsgToCheckIn(user, request);

        sendDisableMsgToHr(user, request);

        sendHrCalculateDaysOff(user, request);
        //工作动态消息
        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            sendApprovalWorkTrendsMsg(request, user, "撤销申请", request.getRequestName());
        }
    }

    /**
     * 删除审批
     *
     * @param user
     * @param request
     */
    public static void sendDeleteMsg(User user, Request request) throws Throwable {
        logger.info("===============删除审批发消息===============");
        clearRequestRedPoint(request.getRequestDkey(), user.getCompanyId());

        sendDisableMsgToCheckIn(user, request);

        sendStatusMsgToUser(request, Constants.DISABLE_STATUS);

        sendDisableMsgToHr(user, request);

        sendHrCalculateDaysOff(user, request);
        //工作动态消息
        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            if (Objects.equals(user.getCompanyInfoId(), request.getApplicantCiid())) {
                RocketUtils.sendApprovalWorkTrendsMsg(request, user, "删除申请", request.getRequestName());
            } else {
                UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
                User applicant = userServicePrx.getUserByContactId(request.getApplicant());
                RocketUtils.sendApprovalWorkTrendsMsg(request, user, "删除" + applicant.getContactName() + "的申请", request.getRequestName());
            }
        }
    }

    /**
     * 提前结束审批
     *
     * @param user
     * @param request
     */
    public static void sendPauseMsg(User user, Request request) throws Throwable {
        logger.info("===============结束审批发消息===============");

        sendStatusMsgToUser(request, Constants.DISABLE_STATUS);

        sendUpdateMsgToHr(request);

        sendHrCalculateDaysOff(user, request);
        //工作动态消息
        if (ApprovalUtils.isTestWorkTrend(user.getCompanyId())) {
            if (Objects.equals(request.getApplicantCiid(), user.getCompanyInfoId())) {
                sendApprovalWorkTrendsMsg(request, user, "提前结束", request.getRequestName());
            } else {
                UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
                User applicant = userServicePrx.getUserByContactId(request.getApplicant());
                sendApprovalWorkTrendsMsg(request, user, "提前结束" + applicant.getContactName() + "的申请", request.getRequestName());
            }
        }
    }

    private static void sendDisableMsgToHr(User user, Request request) {
        if (!LEAVE_TEMPLATE_TYPES.contains(request.getDefaultType())) {
            return;
        }
        logger.info("===============通知人事作废请假流水===============");
        JSONObject jo = new JSONObject();
        jo.put("companyId", user.getCompanyId());
        jo.put("companyInfoId", request.getApplicantCiid());
        jo.put("requestId", request.getRequestDkey());
        MQUtils.sendMessage(Constants.MQ_HR_TOPIC, Constants.MQ_TAGS_DISABLE_LEAVE, jo);
    }

    private static void sendHrCalculateDaysOff(User user, Request request) {
        if (request.getDefaultType() != Template.DAYS_OFF) {
            return;
        }
        JSONObject jo = new JSONObject();
        jo.put("companyId", user.getCompanyId());
        jo.put("companyInfoId", request.getApplicantCiid());

        logger.info("===============通知人事刷新调休时长===============");
        MQUtils.sendMessage(Constants.MQ_HR_TOPIC, Constants.MQ_TAGS_RECALCULATE_DAYS_OFF_TIME, jo);
    }

    private static void sendUpdateMsgToHr(Request request) {
        if (Utils.isNull(request.getLeave())) {
            return;
        }
        logger.info("===============通知人事更新请假流水===============");
        MQUtils.sendMessage(Constants.MQ_HR_TOPIC, Constants.MQ_TAGS_UPDATE_LEAVE, request.getLeave());
    }

    private static void sendConfirmMsgToCheckIn(User user, Request request) {
        if (!CHECK_IN_CONFIRM_TEMPLATE_TYPES.contains(request.getDefaultType())) {
            return;
        }
        logger.info("===============通知考勤已批准审批相关信息===============");
        JSONObject jo = new JSONObject();
        jo.put("requestId", request.getRequestDkey());
        jo.put("companyId", user.getCompanyId());
        jo.put("companyInfoId", request.getApplicantCiid());
        jo.put("defaultType", request.getDefaultType());
        if (Utils.isNotEmpty(request.getOvertimes())) {
            request.getOvertimes().sort(Comparator.comparing(Overtime::getStart));
        }
        jo.put("start", getStartTime(request));
        jo.put("end", getEndTime(request));
        if (request.getDefaultType() == Template.APPEND_SIGN) {
            jo.put("appendSigns", request.getAppendSigns());
        }
        MQUtils.sendMessage(Constants.MQ_CHECK_IN_TOPIC, Constants.MQ_TAGS_CONFIRM_REQUEST, jo);
    }

    private static void sendDisableMsgToCheckIn(User user, Request request) {
        if (!CHECK_IN_DISABLE_TEMPLATE_TYPES.contains(request.getDefaultType())) {
            return;
        }
        logger.info("===============通知考勤审批相关信息失效===============");
        JSONObject jo = new JSONObject();
        jo.put("requestId", request.getRequestDkey());
        jo.put("companyId", user.getCompanyId());
        jo.put("companyInfoId", request.getApplicantCiid());
        jo.put("defaultType", request.getDefaultType());
        jo.put("start", getStartTime(request));
        jo.put("end", getEndTime(request));

        MQUtils.sendMessage(Constants.MQ_CHECK_IN_TOPIC, Constants.MQ_TAGS_DISABLE_REQUEST, jo);
    }

    /**
     * 推送任务团队个人状态
     *
     * @param request
     * @param state
     */
    private static void sendStatusMsgToUser(Request request, Integer state) {
        if (!USER_STATUS_TEMPLATE_TYPES.contains(request.getDefaultType())) {
            return;
        }
        logger.info("===============发消息修改用户状态===============");
        UserStatusDTO userStatusDTO = new UserStatusDTO();
        userStatusDTO.setContactId(request.getApplicant());
        userStatusDTO.setObjectId(request.getRequestDkey());
        Date start = getStartTime(request);
        Date end = getEndTime(request);
        if (Utils.isNull(start) || Utils.isNull(end)) {
            logger.error("数据异常:{}", JSONObject.toJSONString(request));
            EmailUtils.sendMail("修改用户状态异常", request);
            return;
        }

        userStatusDTO.setObjectStartTimeLong(start.getTime());
        userStatusDTO.setObjectEndTimeLong(end.getTime());


        if (request.getDefaultType() == Template.LEAVE
                || request.getDefaultType() == Template.COMPENSATORY_LEAVE) {
            userStatusDTO.setObjectStatus(UserStatus.CASUAL_LEAVE);
        } else if (request.getDefaultType() == Template.OUTDOOR) {
            userStatusDTO.setObjectStatus(UserStatus.BUSINESS_TRIP);
        } else {
            logger.error("错误的状态类型:" + request.getDefaultType());
            return;
        }

        userStatusDTO.setState(state);

        String key = state == Constants.ACTIVE_STATUS ? Constants.MQ_KEYS_APPROVAL_USER_STATUS : Constants.MQ_KEYS_DELETE_USER_STATUS;
        MQUtils.sendMessage(Constants.MQ_TOPIC_USER, Constants.MQ_TAGS_USER_STATUS, key, userStatusDTO);
    }

    private static void pushToNextFlows(User user, Request request, List<Flow> nextFlows) {
        if (Utils.isEmpty(nextFlows)) {
            return;
        }
        try {
            Set<Integer> userIds = new HashSet<>();
            Set<Integer> contactIds = new HashSet<>();
            UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
            for (Flow nextFlow : nextFlows) {
                List<User> users = userServicePrx.getMultiUserListByCompanyInfoId(nextFlow.getCompanyId(), nextFlow.getCompanyInfoId());
                for (User u : users) {
                    userIds.add(u.getUserId());
                    contactIds.add(u.getContactId());
                }
            }
            logger.info("===============推送给下一层审批人:{}===============", userIds);
            RocketUtils.pushApproveRequestMsg(request, userIds);
            RocketUtils.pushToRefresh(user, contactIds);
        } catch (Throwable throwable) {
            logger.error(throwable.getMessage(), throwable);
        }
    }

    /**
     * 获取开始时间
     *
     * @param request
     * @return
     */
    private static Date getStartTime(Request request) {
        if (Utils.isNotNull(request.getLeave())) {
            return request.getLeave().getRealStartTime();
        }
        if (Utils.isNotNull(request.getOutdoor())) {
            return request.getOutdoor().getStart();
        }
        if (Utils.isNotEmpty(request.getOvertimes())) {
            Overtime overtime = Utils.getFirst(request.getOvertimes());
            return Utils.isNull(overtime) ? null : overtime.getStart();
        }
        return null;
    }

    /**
     * 获取结束时间
     *
     * @param request
     * @return
     */
    private static Date getEndTime(Request request) {
        if (Utils.isNotNull(request.getLeave())) {
            return request.getLeave().getRealEndTime();
        }
        if (Utils.isNotNull(request.getOutdoor())) {
            return request.getOutdoor().getEnd();
        }
        if (Utils.isNotEmpty(request.getOvertimes())) {
            Overtime overtime = Utils.getLast(request.getOvertimes());
            return Utils.isNull(overtime) ? null : overtime.getEnd();
        }
        return null;
    }


    /**
     * 提交审批工作动态
     *
     * @param request
     * @param user
     * @param title
     * @param content
     */
    public static void sendApprovalWorkTrendsMsg(Request request, User user, String title, String content) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("companyId", user.getCompanyId());
            jsonObject.put("companyInfoId", user.getCompanyInfoId());
            jsonObject.put("contactId", user.getContactId());
            jsonObject.put("moduleType", "approval");
            jsonObject.put("title", title);
            jsonObject.put("content", content);
            jsonObject.put("workType", "approval");
            jsonObject.put("workId", request.getRequestDkey());
            jsonObject.put("parentId", request.getRequestAncestorId());
            MQUtils.sendMessage(Constants.MQ_TOPIC_APPROVAL_WORK_TRENDS, Constants.MQ_TAG_APPROVAL_WORK_TRENDS, jsonObject);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            MailUtils.sendMail(MailUtils.EMAIL, "消息推送报错", e.getMessage());
        }
    }


}

 